import time
import random

from rest_framework import serializers

from apps.goods.models import Goods
from .models import ShoppingCart, OrderInfo, OrderGoods
from apps.goods.serializers import GoodsSerializer


class ShopCartDetailSerializer(serializers.ModelSerializer):
    goods = GoodsSerializer(many=False, read_only=True)

    class Meta:
        model = ShoppingCart
        fields = ["goods", "nums"]


class ShopCartSerializer(serializers.Serializer):
    # 映射models是的Goods类中的user字段，该字段是默认
    user = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )
    # 映射models是的Goods类中的nums字段,是int类型
    nums = serializers.IntegerField(required=True, label="数量", min_value=1,
                                    error_messages={
                                        "min_value": "商品数量不能小于1",
                                        "required": "请选择购买数量"
                                    })
    # 映射models是的Goods类中的goods字段,是个外键
    goods = serializers.PrimaryKeyRelatedField(required=True, queryset=Goods.objects.all(), label="商品")

    def validate(self, validated_data):
        """
        添加购物车时判断商品库存是否足够
        :param validated_data:
        :return:
        """
        goods_num = validated_data.get("goods").goods_num  # 商品库存数
        trade_num = validated_data.get("nums")  # 添加购物车商品数据量
        if goods_num >= trade_num:
            pass
        else:
            raise serializers.ValidationError(detail="商品库存不足", code="goods_num")
        return validated_data

        # 重写create()方法
        # 加入购物车：场景1：购物车中已经有记录，场景2：购物车中无记录
        # 重写create()方法
        # 加入购物车：场景1：购物车中已经有记录，场景2：购物车中无记录

    def create(self, validated_data):
        user = self.context["request"].user  # 获取当前用户
        nums = validated_data["nums"]
        goods = validated_data["goods"]
        existed = ShoppingCart.objects.filter(user=user, goods=goods)
        if existed:  # 商品已经存在购物车就+1操作
            existed = existed[0]
            existed.nums_news = nums
            existed.nums += nums
            existed.save()
        else:  # 商品不存在，就直接添加到购物车
            existed = ShoppingCart.objects.create(**validated_data)
            existed.nums_news = None
        return existed

    def update(self, instance, validated_data):
        # 修改商品数量
        instance.nums = validated_data["nums"]
        instance.save()
        return instance


class OrderGoodsSerializer(serializers.ModelSerializer):
    goods = GoodsSerializer(many=False)

    class Meta:
        model = OrderGoods
        fields = "__all__"


class OrderDetailSerializer(serializers.ModelSerializer):
    goods = OrderGoodsSerializer(many=True)

    # alipay_url = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = OrderInfo
        fields = "__all__"


class OrderSerializer(serializers.ModelSerializer):
    user = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )
    pay_status = serializers.CharField(read_only=True)  # 只能读不能写
    trade_no = serializers.CharField(read_only=True)  # 只能读不能写
    order_sn = serializers.CharField(read_only=True)  # 只能读不能写
    pay_time = serializers.DateTimeField(read_only=True)

    # alipay_url = serializers.SerializerMethodField(read_only=True)

    def get_alipay_url(self, obj):
        """生成支付宝url"""
        pass

    def generate_order_sn(self):
        """生成订单号 规则：当前时间+userid+随机数"""
        order_sn = "{0}{1}{2}".format(time.strftime("%Y%m%d%H%M%S"), self.context["request"].user.id,
                                      random.randint(10, 99))
        return order_sn

    def validate(self, attrs):
        attrs["order_sn"] = self.generate_order_sn()
        return attrs

    class Meta:
        model = OrderInfo
        fields = "__all__"
